package stone.ast;

import java.util.List;

import ASTInterpreter.ArrayEnv;
import ASTInterpreter.Environment;
import stone.Symbols;
import stone.SymbolThis;

public class DefStmnt extends ASTList {

	protected int index, size;

	public DefStmnt(List<ASTree> list) {
		super(list);
	}
	
	public String name() {
		return ((ASTLeaf)child(0)).token.getText();
	}
	
	public ParameterList parameters() {
		return (ParameterList)child(1);
	}
	
	public BlockStmnt body() {
		return (BlockStmnt)child(2);
	}

	/*
	public Object eval(Environment env) {
		(env).putNew(name(), new Function(parameters(), body(), env));
		return name();
	}
	*/

	public Object eval(Environment env) {
		((ArrayEnv)env).put(0, index, new OptFunction(parameters(), body(), env, size));
		return name();
	}

	public void lookup(Symbols symbols) {
		index = symbols.putNew(name());
		size = Fun.lookup(symbols, parameters(), body());
	}

	public void lookupAsMethod(Symbols symbols) {
		// 以MemberSymbols(FIELD)为外层，创建新的Symbols:newSysmbols
		// 在newSymbols中将(nest=0,index=0)的位置建立"this"的索引
		// 将参数列表和函数体以newSymbols去lookup去更新newSymbols
		Symbols newSymbols = new Symbols(symbols);
		newSymbols.putNew(SymbolThis.NAME);
		parameters().lookup(newSymbols);
		body().lookup(newSymbols);
		size = newSymbols.size();
	}

	public int locals() {
		return size;
	}
	
	public String toString() {
		return "(def " + name() + " " + parameters() + " " + body() + ")";
	}

}
